
import { Injectable } from '@angular/core';
import { Observable, Subject, of } from 'rxjs';
import { map, catchError, tap  } from 'rxjs/operators';

import { HttpHeaders, HttpParams, HttpClient } from '@angular/common/http';

import { User } from '../models/User';
import { Department } from '../models/Department';
import { environment } from '../environments/environment';


@Injectable()
export class LoginService {

  user: User;
  department: Department;
  // store the URL so we can redirect after logging in
  redirectUrl: string;

  private baseUrl =  environment.apiUrl + 'api/user';

  userSource = new Subject<User>();
  departmentSource = new Subject<Department>();
  userObservable = this.userSource.asObservable();

  constructor(
    private http: HttpClient
  ) {

  }

  login(user: User): Observable<{user: User, success: boolean, department: Department}> {
    return this.http.post<{user: User, success: boolean, department: Department}>(this.baseUrl + '/login', user).pipe(tap((res) => {
      if (res.success) {
        this.userSource.next(res.user);
        this.departmentSource.next(res.department);
        this.department = res.department;
      }
    }));
  }

  logout(): Observable<any> {
    this.user = null;
    this.userSource.next(null);
    this.departmentSource.next(null);
    return this.http.get(this.baseUrl + '/logout');
  }

  getCurrent(): Observable< {res: User, success: boolean, department: Department}> {
    return this.http.get<{res: User, success: boolean, department: Department}>(this.baseUrl + '/getuserbysession').pipe(map(res => {
      if (res.success) {
        this.user = res.res;
        this.department = res.department;
        this.userSource.next(this.user);
        this.departmentSource.next(this.department);
      }
      return res;
    }));
  }

}
